const su = require('superagent');
const fs = require('fs');
const yaml = require('yaml');
const Color = require('color');

const url = `https://cdn.clearlywind.com/languages.yml`;

function isDark(color) {
  return Color(color).isDark();
}

async function main() {
  const resp = await su(url);
  let result = [];
  const languages = yaml.parse(resp.text);
  for (let key in languages) {
    let item = languages[key];
    // if (item['type'] === 'programming' && item['color']) {
      if (item.aliases) {
        let aliases = item.aliases;
        for (let i = 0; i < aliases.length; i++) {
          let alias = aliases[i];
          result.push({
            lang: alias,
            tag: alias,
            bg: item.color,
            color: isDark(item.color) ? '#fff' : '#111',
          });
        }
      }
      if (item.extensions) {
        let extensions = item.extensions;
        for (let i = 0; i < extensions; i++) {
          let ext = extensions[i];
          result.push({
            lang: ext,
            tag: ext,
            bg: item.color,
            color: isDark(item.color) ? '#fff' : '#111',
          });
        }
      }
      result.push({
        lang: key,
        tag: Array.isArray(item.aliases)
          ? item.aliases[0]
          : Array.isArray(item.extensions)
          ? item.extensions[0].replace('.', '')
          : '',
        bg: item.color,
        color: isDark(item.color) ? '#fff' : '#111',
      });
    // }
  }
  const template = `const arr = ${JSON.stringify(result)}`;
  fs.writeFileSync('json.js', template);
}

main();
